//
//  CertificationViewController.m
//  JiongTu
//
//  Created by Dupengfei on 16/4/1.
//  Copyright © 2016年 YSKJ. All rights reserved.
//
#define MAX_LIMIT_NUMS 4
#define kAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

#import "CertificationViewController.h"
#import <AVFile.h>
#import <AVObject.h>
#import <AVUser.h>
#import <SVProgressHUD.h>
#import "JTUser.h"
#import <AVOSCloud.h>

@interface CertificationViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate, UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *name;
@property (weak, nonatomic) IBOutlet UITextField *cardId;
@property (weak, nonatomic) IBOutlet UIButton *cardPhoto;
@property (weak, nonatomic) IBOutlet UIButton *cardPhoto1;
@property (weak, nonatomic) IBOutlet UIButton *button;
@property (nonatomic, assign) BOOL maybe;
@property (nonatomic, strong) NSData * data;



@end

@implementation CertificationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initializeInterface];
    
    self.cardId.delegate = self;
}

-(void)initializeInterface
{
    _cardId.keyboardType =UIKeyboardTypeAlphabet;
    self.title = @"实名认证";
    
    if (_cardId.frame.size.width==97) {
        _name.font =[UIFont systemFontOfSize:10];
        _cardId.font =[UIFont systemFontOfSize:10];
    }
    else{
        _name.font =[UIFont systemFontOfSize:14];
    _cardId.font =[UIFont systemFontOfSize:14];
    }
    [_name addTarget:self action:@selector(textFieldshould:) forControlEvents:UIControlEventEditingChanged];
    [_cardId addTarget:self action:@selector(nameTextField:) forControlEvents:UIControlEventEditingChanged];
}
/**
 *  汉字限制输入
 *
 *  @param textFieldshould
 */
-(void)textFieldshould:(UITextField *)textField
{
    NSString *toBeString = textField.text;
    NSArray *currentar = [UITextInputMode activeInputModes];
    UITextInputMode *current = [currentar firstObject];
    
    if ([current.primaryLanguage isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (toBeString.length > 4) {
                textField.text = [toBeString substringToIndex:4];
                [SVProgressHUD showErrorWithStatus:@"输入超过限制！"];
            }
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else{
            
        }
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        if (toBeString.length > 4) {
            textField.text = [toBeString substringToIndex:4];
             [SVProgressHUD showErrorWithStatus:@"输入超过限制！"];
        }
    }
   
}


- (void)nameTextField:(UITextField *)textField
{
    
        if (textField.text.length >18) {
            
            [SVProgressHUD showErrorWithStatus:@"您最多输入18位！"];
            
            textField.text = [textField.text substringToIndex:18];
        
    }
}

#pragma mark-交互事件
/**
 *  照片按钮
 */

- (IBAction)cardPhotopressed:(UIButton *)sender {
    
    _maybe = YES;
    
    [self takePhotoFromPhone];
   
   }

/**
 *  照片交互
 */

- (IBAction)phontoButton:(UIButton *)sender {
    
    _maybe = NO;
    
    [self takePhotoFromPhone];
    
}


/**
 *  提交审核
 */
- (IBAction)buttonPressed:(UIButton *)sender {
    
    NSLog(@"%@",_cardPhoto1.currentImage);
    
    if ([_name.text isEqualToString:@""]) {
        
        [SVProgressHUD showErrorWithStatus:@"姓名不能为空"];
    }
    else if ([_cardId.text isEqualToString:@""])
    {
    [SVProgressHUD showErrorWithStatus:@"身份证号码不能为空"];
    }
    else if (_cardPhoto.currentImage ==nil)
    {
    [SVProgressHUD showErrorWithStatus:@"照片不能为空"];
    }
    else if (_cardPhoto1.currentImage ==nil)
    {
    [SVProgressHUD showErrorWithStatus:@"照片不能为空"];
    }
    else{
    
        [SVProgressHUD showWithStatus:@"正在提交..."];
        
    AVObject * user = [AVObject objectWithoutDataWithClassName:@"_User" objectId:[AVUser currentUser].objectId];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:@"image.png"];
    AVFile *file = [AVFile fileWithName:@"image" contentsAtPath: imagePath];
    
    NSString *imagePath1 = [documentsDirectory stringByAppendingPathComponent:@"image1.png"];
    AVFile *file1 = [AVFile fileWithName:@"image1" contentsAtPath: imagePath1];
    
    NSArray * imageArray =@[file1,file];
    
    [file save];
    
    [file1 save];
    
    [user setObject:_name.text forKey:@"UserTrueName"];
    
    [user setObject:_cardId.text forKey:@"UserTrueId"];
    
    [user setObject:imageArray forKey:@"Image"];
    
    [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        
        if (succeeded) {
            [SVProgressHUD showSuccessWithStatus:@"提交成功，请耐心等待！"];
            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
            [dict setObject:[JTUser currentUser].mobilePhoneNumber forKey:@"phoneNumber"];
//            [dict setObject:user.objectId forKey:@"objectId"];
            
            [AVOSCloud requestSmsCodeWithPhoneNumber:@"15982086828" templateName:@"ID" variables:dict callback:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    [self.navigationController popViewControllerAnimated:YES];
                } else {
                    NSLog(@"%@", error);
                }
            }];
        }
        
        
    }];
    
    }
    
}

#pragma mark-从手机获取照片

-(void)takePhotoFromPhone
{
    UIAlertController * alert =[UIAlertController alertControllerWithTitle:@"提示" message:@"请选择" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * action =[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:imagePickerController animated:YES completion:^{
            
        }];
        
        
    }];
    
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:imagePickerController animated:YES completion:^{
            
        }];
        
        
    }];
    
    UIAlertAction * action2 =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    [alert addAction:action];
    
    [alert addAction:action1];
    
    [alert addAction:action2];
    
    [self presentViewController:alert animated:YES completion:nil];
    
    

}

#pragma mark-delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
        
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    _data = UIImageJPEGRepresentation(image, 0.3);

    //这里将图片放在沙盒的documents文件夹中
    NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
    [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
    [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:_data attributes:nil];
    
    //得到选择后沙盒中图片的完整路径
//   NSString * filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.png"];
    
    if (_maybe==YES) {
        
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:_data attributes:nil];
        [self.cardPhoto setImage:image forState:UIControlStateNormal];
    }
    else
    {
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image1.png"] contents:_data attributes:nil];
    [self.cardPhoto1 setImage:image forState:UIControlStateNormal];
        
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
    
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
    
    BOOL canChange = [string isEqualToString:filtered];
    
    return canChange;
    
}

#pragma mark-回收键盘

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [_name resignFirstResponder];
    
    [_cardId resignFirstResponder];
}

@end
